import { request } from '@/utils/request'
import type { CustomAxiosRequestConfig } from '@/utils/request'
import type { ApiResponse as BaseApiResponse } from '@/types/api'
import type {
  VersionCompletion,
  VersionTransitionRule,
  VersionTransitionReadiness,
  VersionTransitionApproval,
  VersionTransitionRequest,
  VersionTransitionData,
  ApprovalActionData
} from '@/types/version'

// 版本状态类型（动态状态，从状态管理系统获取）
export type VersionStatus = string

// 发布类型枚举 - 与后端完全对齐
export enum ReleaseType {
  MAJOR = 'major',
  MINOR = 'minor',
  PATCH = 'patch',
  HOTFIX = 'hotfix'
}

// 环境枚举 - 与后端完全对齐
export enum Environment {
  DEVELOPMENT = 'development',
  TESTING = 'testing',
  STAGING = 'staging',
  PRODUCTION = 'production'
}

// 发布状态枚举 - 与后端完全对齐
export enum ReleaseStatus {
  PENDING = 'pending',
  IN_PROGRESS = 'in_progress',
  SUCCESS = 'success',
  FAILED = 'failed',
  ROLLED_BACK = 'rolled_back'
}

export type VersionGoalStatus = 'not_started' | 'in_progress' | 'completed'

export interface VersionGoal {
  id?: string
  title: string
  description?: string
  status?: VersionGoalStatus
  owner?: string
  due_date?: string | null
}

// 关联类型枚举 - 与后端完全对齐
export enum RelationType {
  INCLUDED = 'included',
  BLOCKED_BY = 'blocked_by',
  DEPENDS_ON = 'depends_on',
  FOUND_IN = 'found_in',
  FIXED_IN = 'fixed_in'
}

// 发布配置接口 - 与后端ReleaseConfig对齐
export interface ReleaseConfig {
  auto_deploy?: boolean
  rollback_enabled?: boolean
  approval_required?: boolean
  notification_enabled?: boolean
  backup_enabled?: boolean
  health_check_enabled?: boolean
  deployment_strategy?: string
  max_rollback_time?: number
  notification_channels?: string[]
  approval_users?: string[]
}

// 发布元数据接口 - 与后端ReleaseMetadata对齐
export interface ReleaseMetadata {
  build_number?: string
  commit_hash?: string
  branch?: string
  build_url?: string
  deployment_url?: string
  rollback_url?: string
  health_check_url?: string
  documentation_url?: string
  changelog_url?: string
  [key: string]: any
}

// 版本基础接口 - 与后端VersionBase对齐
export interface VersionBase {
  name: string
  version_number: string
  description?: string
  project_id: string
  start_date?: string
  end_date?: string
  status: VersionStatus
  release_type: ReleaseType
  environment: Environment
  planned_release_date?: string
  planned_work_hours?: number
  actual_release_date?: string
  release_notes?: string
  release_config?: ReleaseConfig
  metadata?: ReleaseMetadata
  goals?: VersionGoal[]
  is_pinned?: boolean
}

// 版本创建接口 - 与后端VersionCreate对齐
export interface VersionCreate extends VersionBase {}

// 版本更新接口 - 与后端VersionUpdate对齐
export interface VersionUpdate extends Partial<VersionBase> {}

// 版本接口 - 与后端Version对齐
export interface Version extends VersionBase {
  id: string
  project_name: string
  created_by: string
  created_at: string
  updated_at: string
}

// 版本统计接口 - 与后端VersionWithStats对齐
export interface VersionWithStats extends Version {
  project_name?: string
  task_count: number
  defect_count: number
  release_count: number
  requirement_count?: number
}

// 版本详情响应接口
export interface VersionDetailResponse extends Version {
  project_name: string
  created_by_name: string
  task_count: number
  defect_count: number
  requirement_count: number
  release_history: ReleaseRecord[]
}

export interface VersionProgressStats {
  total: number
  completed: number
}

export interface VersionOverviewItem extends VersionWithStats {
  progress: number
  requirement_stats: VersionProgressStats
  task_stats: VersionProgressStats
  defect_stats: VersionProgressStats
}

export interface VersionOverviewResponse {
  items: VersionOverviewItem[]
  total: number
}

export type VersionWorkItemType = 'requirement' | 'task' | 'defect' | 'group'

export interface VersionWorkItemNode {
  id: string
  type: VersionWorkItemType
  title: string
  status?: string
  priority?: string
  assignee_id?: string | null
  assignee_name?: string | null
  estimated_hours?: number | null
  actual_hours?: number | null
  estimated_effort?: number | null
  start_date?: string | null
  due_date?: string | null
  relation_type?: string | null
  relation_notes?: string | null
  associated_at?: string | null
  severity?: string | null
  requirement_id?: string | null
  task_id?: string | null
  parent_defect_id?: string | null
  meta?: Record<string, any>
  children?: VersionWorkItemNode[]
  leaf?: boolean
  stats?: VersionProgressStats
}

export interface VersionWorkItemsResponse {
  version: {
    id: string
    name: string
    version_number: string
    status: string
    project_id: string
    project_name?: string
    start_date?: string | null
    end_date?: string | null
    planned_release_date?: string | null
    planned_work_hours?: number | null
    progress: number
    requirement_stats: VersionProgressStats
    task_stats: VersionProgressStats
    defect_stats: VersionProgressStats
    goals?: VersionGoal[]
  }
  tree: VersionWorkItemNode[]
  items: {
    requirements: VersionWorkItemNode[]
    tasks: VersionWorkItemNode[]
    defects: VersionWorkItemNode[]
  }
}

export interface VersionPlanTask {
  id: string
  title: string
  status: string | null
  priority?: string | null
  assignee_id?: string | null
  assignee_name?: string | null
  requirement_id?: string | null
  estimated_hours?: number | null
  estimated_effort?: number | null
  actual_hours?: number | null
  start_date?: string | null
  due_date?: string | null
  relation_type?: string | null
  relation_notes?: string | null
  associated_at?: string | null
  reporter_name?: string | null
  reporter_id?: string | null
  created_at?: string | null
  updated_at?: string | null
}

export interface VersionPlanDefect {
  id: string
  title: string
  status: string | null
  priority?: string | null
  severity?: string | null
  assignee_id?: string | null
  assignee_name?: string | null
  requirement_id?: string | null
  task_id?: string | null
  parent_defect_id?: string | null
  found_date?: string | null
  resolved_date?: string | null
  relation_type?: string | null
  relation_notes?: string | null
  associated_at?: string | null
  reporter_name?: string | null
  reporter_id?: string | null
  created_at?: string | null
  updated_at?: string | null
}

export interface VersionPlanRequirement {
  id: string
  title: string
  status: string | null
  priority?: string | null
  assignee_id?: string | null
  assignee_name?: string | null
  estimated_effort?: number | null
  start_date?: string | null
  due_date?: string | null
  relation_type?: string | null
  relation_notes?: string | null
  associated_at?: string | null
  reporter_name?: string | null
  reporter_id?: string | null
  creator_id?: string | null
  creator_name?: string | null
  created_at?: string | null
  updated_at?: string | null
  task_count: number
  defect_count: number
  tasks: VersionPlanTask[]
  defects: VersionPlanDefect[]
}

export interface VersionPlanSummary {
  total_work_items: number
  total_requirements: number
  total_tasks: number
  total_defects: number
  status_breakdown: {
    requirements: Record<string, number>
    tasks: Record<string, number>
    defects: Record<string, number>
  }
}

export interface VersionPlanVersion {
  id: string
  name: string
  version_number: string
  status: string
  project_id: string
  project_name?: string
  start_date?: string | null
  end_date?: string | null
  planned_release_date?: string | null
  planned_work_hours?: number | null
  progress: number
  requirement_stats: VersionProgressStats
  task_stats: VersionProgressStats
  defect_stats: VersionProgressStats
  goals?: VersionGoal[]
  description?: string | null
  created_by?: string
}

export interface VersionPlanResponse {
  version: VersionPlanVersion
  summary: VersionPlanSummary
  requirements: VersionPlanRequirement[]
  unassigned: {
    tasks: VersionPlanTask[]
    defects: VersionPlanDefect[]
  }
}

export interface VersionKanbanItem {
  id: string
  title: string
  status: string | null
  priority?: string | null
  severity?: string | null
  assignee_id?: string | null
  assignee_name?: string | null
  due_date?: string | null
  start_date?: string | null
  requirement_id?: string | null
  task_id?: string | null
  type: 'requirement' | 'task' | 'defect'
  meta?: Record<string, any>
}

export interface VersionKanbanColumn {
  status: string
  title: string
  items: VersionKanbanItem[]
}

export interface VersionKanbanResponse {
  version: VersionWorkItemsResponse['version']
  dimension: 'requirement' | 'task' | 'defect'
  columns: VersionKanbanColumn[]
  meta: {
    filters: Record<string, any>
    stats: {
      total: number
      by_status: Record<string, number>
    }
  }
}

// 版本比较响应接口
export interface VersionCompareResponse {
  source_version: Version
  target_version: Version
  differences: {
    tasks: {
      added: any[]
      removed: any[]
      modified: any[]
    }
    defects: {
      added: any[]
      removed: any[]
      resolved: any[]
    }
    requirements: {
      added: any[]
      removed: any[]
      modified: any[]
    }
  }
  summary: {
    total_changes: number
    task_changes: number
    defect_changes: number
    requirement_changes: number
  }
}

// 版本关联信息接口
export interface VersionAssociation {
  id: string
  version_id: string
  entity_type: 'task' | 'defect' | 'requirement'
  entity_id: string
  entity_title: string
  entity_status: string
  associated_at: string
  associated_by: string
}

// 版本任务关联接口
export interface VersionTaskRelation {
  id: string
  version_id: string
  task_id: string
  task_title: string
  task_status: string
  task_assignee?: string | null
  task_assignee_name?: string | null
  requirement_id?: string | null
  requirement_title?: string | null
  relation_type: RelationType
  associated_at: string
  associated_by: string
  notes?: string
}

// 版本任务关联创建接口
export interface VersionTaskRelationCreate {
  task_id: string
  requirement_id?: string
  relation_type: RelationType
  notes?: string
}

// 版本缺陷关联接口
export interface VersionDefectRelation {
  id: string
  version_id: string
  defect_id: string
  defect_title: string
  defect_status: string
  defect_assignee?: string | null
  defect_assignee_name?: string | null
  requirement_id?: string | null
  requirement_title?: string | null
  task_id?: string | null
  task_title?: string | null
  parent_defect_id?: string | null
  parent_defect_title?: string | null
  relation_type: RelationType
  associated_at: string
  associated_by: string
  notes?: string
}

// 版本缺陷关联创建接口
export interface VersionDefectRelationCreate {
  defect_id: string
  requirement_id?: string
  task_id?: string
  parent_defect_id?: string
  relation_type: RelationType
  notes?: string
}

// 版本需求关联接口
export interface VersionRequirement {
  id: string
  version_id: string
  requirement_id: string
  requirement_title: string
  requirement_status: string
  relation_type: RelationType
  associated_at: string
  associated_by: string
}

// 版本需求关联创建接口
export interface VersionRequirementCreate {
  requirement_id: string
  relation_type: RelationType
  notes?: string
}

// 发布请求接口
export interface ReleaseRequest {
  release_notes?: string
  environment: Environment
  release_config?: ReleaseConfig
  metadata?: ReleaseMetadata
}

// 回滚请求接口
export interface RollbackRequest {
  rollback_reason: string
  target_version_id?: string
  rollback_config?: any
}

// 发布记录接口
export interface ReleaseRecord {
  id: string
  version_id: string
  release_date: string
  release_notes?: string
  environment: Environment
  released_by: string
  released_by_name?: string
  status: ReleaseStatus
  rollback_reason?: string
  deployment_log?: string
  metadata?: ReleaseMetadata
}

// 版本统计报告接口
export interface VersionStatistics {
  total_versions: number
  versions_by_status: Record<VersionStatus, number>
  versions_by_project: Array<{
    project_id: string
    project_name: string
    version_count: number
  }>
  release_metrics: {
    total_releases: number
    successful_releases: number
    failed_releases: number
    rollback_count: number
    avg_release_time: number
  }
  quality_metrics: {
    avg_defect_count: number
    avg_task_completion_rate: number
    avg_test_coverage: number
  }
}

// 质量指标接口
export interface QualityMetrics {
  defect_density: number
  test_coverage: number
  code_quality_score: number
  performance_score: number
  security_score: number
  maintainability_score: number
}

// 批量操作结果接口
export interface BulkOperationResult {
  success_count: number
  failed_count: number
  total_count: number
  failed_items?: Array<{
    id: string
    error: string
  }>
}

// 影响分析结果接口
export interface ImpactAnalysis {
  version_id: string
  direct_impact: {
    tasks: number
    defects: number
    requirements: number
  }
  indirect_impact: {
    dependent_versions: string[]
    affected_projects: string[]
    risk_level: 'low' | 'medium' | 'high'
  }
  recommendations: string[]
}

// 变更历史记录接口
export interface ChangeHistory {
  timestamp: string
  action: string
  details: Record<string, any>
  user_id: string
  type: string
}

// 版本变更历史响应接口
export interface VersionChangeHistoryResponse {
  version_info: {
    id: string
    name: string
    version_number: string
  }
  change_history: ChangeHistory[]
  total_changes: number
}

// 发布计划接口
export interface ReleasePlan {
  id: string
  name: string
  description?: string
  version_ids: string[]
  planned_date: string
  environment: Environment
  status: 'draft' | 'pending_approval' | 'approved' | 'rejected' | 'executed'
  created_by: string
  created_at: string
  approved_by?: string
  approved_at?: string
  approval_comments?: string
}

// 审批数据接口
export interface ApprovalData {
  approved: boolean
  comments?: string
  conditions?: string[]
}

// 性能统计接口
export interface PerformanceStats {
  query_performance: {
    avg_response_time: number
    total_queries: number
    slow_queries: number
  }
  resource_usage: {
    memory_usage: number
    cpu_usage: number
    disk_usage: number
  }
  cache_performance: {
    hit_rate: number
    miss_rate: number
    eviction_rate: number
  }
}

// API请求参数接口
export interface GetVersionsParams {
  skip?: number
  limit?: number
  page?: number
  size?: number
  search?: string
  project_id?: string
  status?: VersionStatus
  release_type?: ReleaseType
  environment?: Environment
  created_by?: string
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

export interface GetVersionsOverviewParams {
  project_id?: string
  status?: string
  release_type?: ReleaseType
  environment?: Environment
  created_by?: string
  limit?: number
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

export interface GetVersionsCountParams {
  project_id?: string
  status?: VersionStatus
  search?: string
}

export interface GetVersionTasksParams {
  skip?: number
  limit?: number
  status?: string
  relation_type?: RelationType
}

export interface GetVersionDefectsParams {
  skip?: number
  limit?: number
  status?: string
  relation_type?: RelationType
}

export interface GetVersionRequirementsParams {
  skip?: number
  limit?: number
  status?: string
  relation_type?: RelationType
}

export interface VersionCompareParams {
  include_tasks?: boolean
  include_defects?: boolean
  include_requirements?: boolean
}

export interface VersionAnalyticsParams {
  project_id?: string
  start_date?: string
  end_date?: string
  include_quality_metrics?: boolean
}

export interface VersionStatisticsParams {
  project_id?: string
  start_date?: string
  end_date?: string
  status?: VersionStatus[]
}

export interface QualityMetricsParams {
  project_id?: string
  version_ids?: string[]
  metric_types?: string[]
}

export interface ImpactAnalysisParams {
  depth?: number
  include_dependencies?: boolean
  include_dependents?: boolean
}

export interface ChangeHistoryParams {
  limit?: number
  offset?: number
  change_type?: string[]
}

export interface PerformanceStatsParams {
  time_range?: string
  metrics?: string[]
}

// API响应接口 - 使用别名避免与导入冲突
export type ApiResponse<T> = BaseApiResponse<T>

export interface PaginatedResponse<T> {
  items: T[]
  pagination: {
    page: number
    size: number
    total: number
    pages: number
    has_prev?: boolean
    has_next?: boolean
  }
}

/**
 * 处理API响应，统一转换为ApiResponse格式
 */
interface AxiosResponseData<T> {
  success?: boolean
  code?: number
  message?: string
  data?: T
  pagination?: {
    page: number
    size: number
    total: number
    pages: number
    has_prev?: boolean
    has_next?: boolean
  }
}

interface AxiosResponseWrapper<T> {
  status?: number
  statusText?: string
  data?: AxiosResponseData<T>
}

function handleApiResponse<T>(response: AxiosResponseWrapper<T>, defaultData: T): ApiResponse<T> {
  if (response.data && response.data.success) {
    return {
      status: response.status || 200,
      statusText: response.statusText || 'OK',
      success: response.data.success,
      code: response.data.code || 200,
      message: response.data.message || '请求成功',
      data: response.data.data || defaultData,
      pagination: response.data.pagination,
      timestamp: new Date().toISOString()
    }
  }
  // 确保始终返回ApiResponse格式
  return {
    status: response.status || 500,
    statusText: response.statusText || 'Internal Server Error',
    success: false,
    code: response.data?.code || 500,
    message: response.data?.message || '请求失败',
    data: defaultData,
    timestamp: new Date().toISOString()
  }
}

/**
 * 从响应中提取数据，如果失败则返回默认值
 */
function extractResponseData<T>(response: AxiosResponseWrapper<T>, defaultData: T): T {
  if (response.data && response.data.success && response.data.data) {
    return response.data.data
  }
  return defaultData
}

// 版本管理API类
class VersionAPI {
  // 获取版本列表 - GET /versions
  async getVersions(params: GetVersionsParams = {}): Promise<ApiResponse<PaginatedResponse<VersionWithStats>>> {
    // 转换参数格式：前端使用page/size，后端使用skip/limit
    const requestParams: Record<string, string | number> = {}
    if (params.skip !== undefined) requestParams.skip = params.skip
    if (params.limit !== undefined) requestParams.limit = params.limit
    if (params.page !== undefined && params.size !== undefined) {
      requestParams.skip = (params.page - 1) * params.size
      requestParams.limit = params.size
    }
    if (params.search && params.search.trim()) requestParams.search = params.search
    if (params.project_id && params.project_id.trim()) requestParams.project_id = params.project_id
    if (params.status) requestParams.status = params.status
    if (params.release_type) requestParams.release_type = params.release_type
    if (params.environment) requestParams.environment = params.environment
    if (params.created_by && params.created_by.trim()) requestParams.created_by = params.created_by
    if (params.sort_by) requestParams.sort_by = params.sort_by
    if (params.sort_order) requestParams.sort_order = params.sort_order

    const response = await request<ApiResponse<PaginatedResponse<VersionWithStats>>>({
      url: '/versions',
      method: 'get',
      params: requestParams
    })
    
    // 后端返回格式：{success: true, data: [...], pagination: {...}}
    // 需要转换为前端期望的格式：{success: true, data: {items: [...], pagination: {...}}}
    if (response.data && response.data.success) {
      // 如果data是数组，说明后端返回的是旧格式，需要转换
      if (Array.isArray(response.data.data)) {
        const pagination = response.data.pagination || {
          page: 1,
          size: 20,
          total: Array.isArray(response.data.data) ? response.data.data.length : 0,
          pages: 1
        }
        return {
          ...response.data,
          data: {
            items: response.data.data,
            pagination
          }
        } as ApiResponse<PaginatedResponse<VersionWithStats>>
      }
      // 如果data已经是PaginatedResponse格式，直接返回
      if (response.data.data && typeof response.data.data === 'object' && 'items' in response.data.data) {
        return response.data as ApiResponse<PaginatedResponse<VersionWithStats>>
      }
      // 如果data不存在或格式不对，返回空结果
      return {
        ...response.data,
        data: {
          items: [],
          pagination: {
            page: 1,
            size: 20,
            total: 0,
            pages: 1
          }
        }
      } as ApiResponse<PaginatedResponse<VersionWithStats>>
    }
    
    // 如果响应格式不对，返回空结果
    return {
      success: false,
      status: response?.status || 500,
      statusText: response?.statusText || 'Internal Server Error',
      code: response?.data?.code || 500,
      message: response?.data?.message || '获取版本列表失败',
      data: {
        items: [],
        pagination: {
          page: 1,
          size: 20,
          total: 0,
          pages: 1
        }
      },
      timestamp: new Date().toISOString()
    } as ApiResponse<PaginatedResponse<VersionWithStats>>
  }

  // 获取版本总览 - GET /versions/overview
  async getVersionsOverview(params: GetVersionsOverviewParams = {}): Promise<ApiResponse<VersionOverviewResponse>> {
    const response = await request<ApiResponse<VersionOverviewResponse>>({
      url: '/versions/overview',
      method: 'get',
      params
    })
    return handleApiResponse(response, { items: [], total: 0 } as VersionOverviewResponse)
  }

  // 获取版本数量 - GET /versions/count
  async getVersionsCount(params: GetVersionsCountParams = {}): Promise<ApiResponse<{ count: number }>> {
    const requestParams: Record<string, string> = {}
    if (params.search && params.search.trim()) requestParams.search = params.search
    if (params.project_id && params.project_id.trim()) requestParams.project_id = params.project_id
    if (params.status) requestParams.status = params.status

    const response = await request<ApiResponse<{ count: number }>>({
      url: '/versions/count',
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, { count: 0 })
  }

  // 获取版本详情 - GET /versions/{id}
  async getVersionById(
    versionId: string,
    params: { include_tasks?: boolean } = {}
  ): Promise<ApiResponse<VersionDetailResponse & { relations?: { tasks?: VersionTaskRelation[] } }>> {
    const response = await request<ApiResponse<VersionDetailResponse & { relations?: { tasks?: VersionTaskRelation[] } }>>({
      url: `/versions/${versionId}`,
      method: 'get',
      params
    })
    
    return handleApiResponse(response, {} as VersionDetailResponse & { relations?: { tasks?: VersionTaskRelation[] } })
  }

  // 获取版本工作项树 - GET /versions/{id}/work-items
  async getVersionWorkItems(versionId: string): Promise<ApiResponse<VersionWorkItemsResponse>> {
    const response = await request<ApiResponse<VersionWorkItemsResponse>>({
      url: `/versions/${versionId}/work-items`,
      method: 'get'
    })
    return handleApiResponse(response, { version: {} as any, tree: [], items: { requirements: [], tasks: [], defects: [] } } as VersionWorkItemsResponse)
  }

  // 获取版本规划视图数据 - GET /versions/{id}/plan
  async getVersionPlan(versionId: string): Promise<ApiResponse<VersionPlanResponse>> {
    const response = await request<ApiResponse<VersionPlanResponse>>({
      url: `/versions/${versionId}/plan`,
      method: 'get'
    })
    return handleApiResponse(response, { version: {} as any, summary: {} as any, requirements: [], unassigned: { tasks: [], defects: [] } } as VersionPlanResponse)
  }

  // 获取版本看板数据 - GET /versions/{id}/kanban
  async getVersionKanban(
    versionId: string,
    params: {
      dimension?: 'requirement' | 'task' | 'defect'
      status?: string | string[]
      assignee_id?: string
    } = {}
  ): Promise<ApiResponse<VersionKanbanResponse>> {
    const query: Record<string, string> = {}
    if (params.dimension) query.dimension = params.dimension
    if (params.status) {
      query.status = Array.isArray(params.status) ? params.status.join(',') : params.status
    }
    if (params.assignee_id) query.assignee_id = params.assignee_id

    const response = await request<ApiResponse<VersionKanbanResponse>>({
      url: `/versions/${versionId}/kanban`,
      method: 'get',
      params: query
    })
    return handleApiResponse(response, { version: {} as any, dimension: 'task', columns: [], meta: { filters: {}, stats: { total: 0, by_status: {} } } } as VersionKanbanResponse)
  }

  // 创建版本 - POST /versions
  async createVersion(data: VersionCreate): Promise<ApiResponse<Version>> {
    const response = await request<ApiResponse<Version>>({
      url: '/versions',
      method: 'post',
      data
    })
    
    return handleApiResponse(response, {} as Version)
  }

  // 更新版本 - PUT /versions/{id}
  async updateVersion(versionId: string, data: VersionUpdate): Promise<ApiResponse<Version>> {
    const response = await request<ApiResponse<Version>>({
      url: `/versions/${versionId}`,
      method: 'put',
      data
    })
    
    return handleApiResponse(response, {} as Version)
  }

  // 删除版本 - DELETE /versions/{id}
  async deleteVersion(versionId: string): Promise<ApiResponse<void>> {
    const response = await request<ApiResponse<void>>({
      url: `/versions/${versionId}`,
      method: 'delete'
    })
    
    return handleApiResponse(response, undefined as void)
  }

  // 发布版本 - POST /versions/{id}/release
  async releaseVersion(versionId: string, data: ReleaseRequest): Promise<ApiResponse<ReleaseRecord>> {
    const response = await request<ApiResponse<ReleaseRecord>>({
      url: `/versions/${versionId}/release`,
      method: 'post',
      data
    })
    
    return handleApiResponse(response, {} as ReleaseRecord)
  }

  // 回滚版本 - POST /versions/{id}/rollback
  async rollbackVersion(versionId: string, data: RollbackRequest): Promise<ApiResponse<ReleaseRecord>> {
    const response = await request<ApiResponse<ReleaseRecord>>({
      url: `/versions/${versionId}/rollback`,
      method: 'post',
      data
    })
    
    return handleApiResponse(response, {} as ReleaseRecord)
  }

  // 添加任务到版本 - POST /versions/{version_id}/tasks
  async addTaskToVersion(versionId: string, data: VersionTaskRelationCreate, config?: CustomAxiosRequestConfig): Promise<VersionTaskRelation> {
    const response = await request<ApiResponse<VersionTaskRelation>>({
      url: `/versions/${versionId}/tasks`,
      method: 'post',
      data,
      ...config
    })
    
    const result = extractResponseData(response, {} as VersionTaskRelation)
    if (!result || Object.keys(result).length === 0) {
      throw new Error(response.data?.message || '添加任务关联失败')
    }
    return result
  }

  // 从版本移除任务 - DELETE /versions/{version_id}/tasks/{task_id}
  async removeTaskFromVersion(versionId: string, taskId: string): Promise<ApiResponse<void>> {
    const response = await request<ApiResponse<void>>({
      url: `/versions/${versionId}/tasks/${taskId}`,
      method: 'delete'
    })
    
    return handleApiResponse(response, undefined as void)
  }

  // 添加缺陷到版本 - POST /versions/{version_id}/defects
  async addDefectToVersion(versionId: string, data: VersionDefectRelationCreate, config?: CustomAxiosRequestConfig): Promise<VersionDefectRelation> {
    const response = await request<ApiResponse<VersionDefectRelation>>({
      url: `/versions/${versionId}/defects`,
      method: 'post',
      data,
      ...config
    })
    
    const result = extractResponseData(response, {} as VersionDefectRelation)
    if (!result || Object.keys(result).length === 0) {
      throw new Error(response.data?.message || '添加缺陷关联失败')
    }
    return result
  }

  // 从版本移除缺陷 - DELETE /versions/{version_id}/defects/{defect_id}
  async removeDefectFromVersion(versionId: string, defectId: string): Promise<ApiResponse<void>> {
    const response = await request<ApiResponse<void>>({
      url: `/versions/${versionId}/defects/${defectId}`,
      method: 'delete'
    })
    
    return handleApiResponse(response, undefined as void)
  }

  // 比较版本 - GET /versions/{version_id}/compare/{target_version_id}
  async compareVersions(sourceId: string, targetId: string, params: VersionCompareParams = {}): Promise<ApiResponse<VersionCompareResponse>> {
    const requestParams: Record<string, boolean> = {}
    if (params.include_tasks !== undefined) requestParams.include_tasks = params.include_tasks
    if (params.include_defects !== undefined) requestParams.include_defects = params.include_defects
    if (params.include_requirements !== undefined) requestParams.include_requirements = params.include_requirements

    const response = await request<ApiResponse<VersionCompareResponse>>({
      url: `/versions/${sourceId}/compare/${targetId}`,
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, { source_version: {} as any, target_version: {} as any, differences: { tasks: { added: [], removed: [], modified: [] }, defects: { added: [], removed: [], resolved: [] }, requirements: { added: [], removed: [], modified: [] } }, summary: { total_changes: 0, task_changes: 0, defect_changes: 0, requirement_changes: 0 } } as VersionCompareResponse)
  }

  // 获取版本统计 - GET /versions/statistics
  async getVersionStatistics(params: VersionStatisticsParams = {}): Promise<ApiResponse<VersionStatistics>> {
    const requestParams: Record<string, string | string[]> = {}
    if (params.project_id && params.project_id.trim()) requestParams.project_id = params.project_id
    if (params.start_date) requestParams.start_date = params.start_date
    if (params.end_date) requestParams.end_date = params.end_date
    if (params.status && params.status.length > 0) requestParams.status = params.status

    const response = await request<ApiResponse<VersionStatistics>>({
      url: '/versions/statistics',
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, { 
      total_versions: 0, 
      versions_by_status: {} as Record<VersionStatus, number>, 
      versions_by_project: [], 
      release_metrics: { total_releases: 0, successful_releases: 0, failed_releases: 0, rollback_count: 0, avg_release_time: 0 }, 
      quality_metrics: { avg_defect_count: 0, avg_task_completion_rate: 0, avg_test_coverage: 0 } 
    } as VersionStatistics)
  }

  // 添加需求到版本 - POST /versions/{version_id}/requirements
  async addRequirementToVersion(versionId: string, data: VersionRequirementCreate): Promise<ApiResponse<VersionRequirement>> {
    const response = await request<ApiResponse<VersionRequirement>>({
      url: `/versions/${versionId}/requirements`,
      method: 'post',
      data
    })
    
    return handleApiResponse(response, {} as VersionRequirement)
  }

  // 从版本移除需求 - DELETE /versions/{version_id}/requirements/{requirement_id}
  async removeRequirementFromVersion(versionId: string, requirementId: string): Promise<ApiResponse<void>> {
    const response = await request<ApiResponse<void>>({
      url: `/versions/${versionId}/requirements/${requirementId}`,
      method: 'delete'
    })
    
    return handleApiResponse(response, undefined as void)
  }

  // 获取版本需求 - GET /versions/{version_id}/requirements
  async getVersionRequirements(versionId: string, params: GetVersionRequirementsParams = {}): Promise<ApiResponse<VersionRequirement[]>> {
    const requestParams: Record<string, string | number> = {}
    if (params.skip !== undefined) requestParams.skip = params.skip
    if (params.limit !== undefined) requestParams.limit = params.limit
    if (params.status) requestParams.status = params.status
    if (params.relation_type) requestParams.relation_type = params.relation_type

    const response = await request<ApiResponse<VersionRequirement[]>>({
      url: `/versions/${versionId}/requirements`,
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, [] as VersionRequirement[])
  }

  // 获取版本所有关联项 - GET /versions/{version_id}/associations
  async getVersionAssociations(
    versionId: string,
    entityType?: 'task' | 'defect' | 'requirement',
    params?: {
      skip?: number
      limit?: number
    }
  ): Promise<ApiResponse<PaginatedResponse<VersionTaskRelation | VersionDefectRelation | VersionRequirement>>> {
    const requestParams: Record<string, string | number> = {}
    if (entityType) requestParams.entity_type = entityType
    if (params?.skip !== undefined) requestParams.skip = params.skip
    if (params?.limit !== undefined) requestParams.limit = params.limit

    const response = await request<ApiResponse<PaginatedResponse<VersionTaskRelation | VersionDefectRelation | VersionRequirement>>>({
      url: `/versions/${versionId}/associations`,
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, {
      items: [],
      pagination: {
        page: 1,
        size: 20,
        total: 0,
        pages: 1
      }
    })
  }

  // 移除版本关联项 - DELETE /versions/{version_id}/associations/{entity_type}/{entity_id}
  async removeVersionAssociation(
    versionId: string,
    entityType: 'task' | 'defect' | 'requirement',
    entityId: string
  ): Promise<ApiResponse<void>> {
    const response = await request<ApiResponse<void>>({
      url: `/versions/${versionId}/associations/${entityType}/${entityId}`,
      method: 'delete'
    })
    
    return handleApiResponse(response, undefined as void)
  }

  // 搜索关联项 - GET /versions/{version_id}/associations/search
  async searchAssociationItems(
    entityType: 'task' | 'defect' | 'requirement',
    params: {
      search?: string
      exclude_version_id?: string
      limit?: number
      project_id?: string
    }
  ): Promise<ApiResponse<PaginatedResponse<any>>> {
    const requestParams: Record<string, string | number> = {}
    if (params.search) requestParams.search = params.search
    if (params.exclude_version_id) requestParams.exclude_version_id = params.exclude_version_id
    if (params.limit) requestParams.limit = params.limit
    if (params.project_id) requestParams.project_id = params.project_id

    // 根据类型调用不同的搜索端点
    let url = ''
    switch (entityType) {
      case 'task':
        url = '/tasks/search'
        break
      case 'defect':
        url = '/defects/search'
        break
      case 'requirement':
        url = '/requirements/search'
        break
    }

    const response = await request<ApiResponse<PaginatedResponse<any>>>({
      url,
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, {
      items: [],
      pagination: {
        page: 1,
        size: 20,
        total: 0,
        pages: 1
      }
    })
  }

  // 批量添加版本关联 - POST /versions/{version_id}/associations/batch
  async addVersionAssociations(
    versionId: string,
    entityType: 'task' | 'defect' | 'requirement',
    entityIds: string[]
  ): Promise<ApiResponse<BulkOperationResult>> {
    const response = await request<ApiResponse<BulkOperationResult>>({
      url: `/versions/${versionId}/associations/batch`,
      method: 'post',
      data: {
        entity_type: entityType,
        entity_ids: entityIds
      }
    })
    
    return handleApiResponse(response, {
      success_count: 0,
      failed_count: 0,
      total_count: 0
    })
  }

  // 获取版本分析概览 - GET /versions/analytics/overview
  async getVersionAnalytics(params: VersionAnalyticsParams = {}): Promise<ApiResponse<any>> {
    const requestParams: any = {}
    if (params.project_id && params.project_id.trim()) requestParams.project_id = params.project_id
    if (params.start_date) requestParams.start_date = params.start_date
    if (params.end_date) requestParams.end_date = params.end_date
    if (params.include_quality_metrics !== undefined) requestParams.include_quality_metrics = params.include_quality_metrics

    const response = await request<ApiResponse<any>>({
      url: '/versions/analytics/overview',
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, {} as any)
  }

  // 获取版本质量指标 - GET /versions/analytics/quality-metrics
  async getVersionQualityMetrics(params: QualityMetricsParams = {}): Promise<ApiResponse<QualityMetrics>> {
    const requestParams: any = {}
    if (params.project_id && params.project_id.trim()) requestParams.project_id = params.project_id
    if (params.version_ids && params.version_ids.length > 0) requestParams.version_ids = params.version_ids
    if (params.metric_types && params.metric_types.length > 0) requestParams.metric_types = params.metric_types

    const response = await request<ApiResponse<QualityMetrics>>({
      url: '/versions/analytics/quality-metrics',
      method: 'get',
      params: requestParams
    })
    
    return handleApiResponse(response, { defect_density: 0, test_coverage: 0, code_quality_score: 0, performance_score: 0, security_score: 0, maintainability_score: 0 } as QualityMetrics)
  }

  // 批量更新版本状态 - POST /versions/bulk/update-status
  async bulkUpdateVersionStatus(versionIds: string[], status: VersionStatus): Promise<ApiResponse<BulkOperationResult>> {
    const response = await request<ApiResponse<BulkOperationResult>>({
      url: '/versions/bulk/update-status',
      method: 'post',
      data: {
        version_ids: versionIds,
        new_status: status
      }
    })
    
    return handleApiResponse(response, { success_count: 0, failed_count: 0, total_count: 0 } as BulkOperationResult)
  }

  // 批量删除版本 - DELETE /versions/bulk/delete
  async bulkDeleteVersions(versionIds: string[]): Promise<ApiResponse<BulkOperationResult>> {
    const response = await request<ApiResponse<BulkOperationResult>>({
      url: '/versions/bulk/delete',
      method: 'delete',
      data: { version_ids: versionIds }
    })
    
    return handleApiResponse(response, { success_count: 0, failed_count: 0, total_count: 0 } as BulkOperationResult)
  }

  // 批量关联任务 - POST /versions/bulk/associate-tasks
  async bulkAssociateTasks(versionIds: string[], taskIds: string[]): Promise<ApiResponse<BulkOperationResult>> {
    const response = await request<ApiResponse<BulkOperationResult>>({
      url: '/versions/bulk/associate-tasks',
      method: 'post',
      data: {
        version_ids: versionIds,
        task_ids: taskIds
      }
    })
    
    return handleApiResponse(response, { success_count: 0, failed_count: 0, total_count: 0 } as BulkOperationResult)
  }

  // 获取版本依赖关系 - GET /versions/dependencies/{version_id}
  async getVersionDependencies(versionId: string, depth: number = 3): Promise<any> {
    const response = await request.get<ApiResponse<any>>(`/versions/dependencies/${versionId}`, {
      params: { depth },
      showLoading: true,
      loadingText: '加载依赖关系...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {} as any)
  }

  // 获取版本影响分析 - GET /versions/impact-analysis/{version_id}
  async getVersionImpactAnalysis(versionId: string, params: ImpactAnalysisParams = {}): Promise<ImpactAnalysis> {
    const response = await request.get<ApiResponse<ImpactAnalysis>>(`/versions/impact-analysis/${versionId}`, {
      params,
      showLoading: true,
      loadingText: '分析版本影响...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {
      version_id: versionId,
      direct_impact: {
        tasks: 0,
        defects: 0,
        requirements: 0
      },
      indirect_impact: {
        dependent_versions: [],
        affected_projects: [],
        risk_level: 'low' as const
      },
      recommendations: []
    } as ImpactAnalysis)
  }

  // 获取版本变更历史 - GET /versions/change-history/{version_id}
  async getVersionChangeHistory(versionId: string, params: ChangeHistoryParams = {}): Promise<VersionChangeHistoryResponse> {
    const response = await request.get<ApiResponse<VersionChangeHistoryResponse>>(`/versions/change-history/${versionId}`, {
      params,
      showLoading: true,
      loadingText: '加载变更历史...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {
      version_info: {
        id: versionId,
        name: '',
        version_number: ''
      },
      change_history: [],
      total_changes: 0
    } as VersionChangeHistoryResponse)
  }

  // 创建发布计划 - POST /versions/release-plans
  async createReleasePlan(data: any): Promise<ReleasePlan> {
    const response = await request.post<ApiResponse<ReleasePlan>>('/versions/release-plans', data, {
      showLoading: true,
      loadingText: '创建发布计划...',
      showSuccess: true,
      successText: '发布计划创建成功'
    } as CustomAxiosRequestConfig)
    const result = extractResponseData(response, {} as ReleasePlan)
    if (!result || Object.keys(result).length === 0) {
      throw new Error(response.data?.message || '创建发布计划失败')
    }
    return result
  }

  // 获取发布计划列表 - GET /versions/release-plans
  async getReleasePlans(params: any = {}): Promise<ReleasePlan[]> {
    const response = await request.get<ApiResponse<ReleasePlan[]>>('/versions/release-plans', {
      params,
      showLoading: true,
      loadingText: '加载发布计划...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, [] as ReleasePlan[])
  }

  // 审批发布计划 - POST /versions/release-plans/{plan_id}/approve
  async approveReleasePlan(planId: string, data: ApprovalData): Promise<ReleasePlan> {
    const response = await request.post<ApiResponse<ReleasePlan>>(`/versions/release-plans/${planId}/approve`, data, {
      showLoading: true,
      loadingText: '审批发布计划...',
      showSuccess: true,
      successText: '审批完成'
    } as CustomAxiosRequestConfig)
    const result = extractResponseData(response, {} as ReleasePlan)
    if (!result || Object.keys(result).length === 0) {
      throw new Error(response.data?.message || '审批发布计划失败')
    }
    return result
  }

  // 获取性能统计 - GET /versions/performance/query-stats
  async getVersionPerformanceStats(params: PerformanceStatsParams = {}): Promise<PerformanceStats> {
    const response = await request.get<ApiResponse<PerformanceStats>>('/versions/performance/query-stats', {
      params,
      showLoading: true,
      loadingText: '加载性能统计...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {
      query_performance: {
        avg_response_time: 0,
        total_queries: 0,
        slow_queries: 0
      },
      resource_usage: {
        cpu_usage: 0,
        memory_usage: 0,
        disk_usage: 0
      },
      cache_performance: {
        hit_rate: 0,
        miss_rate: 0,
        eviction_rate: 0
      }
    } as PerformanceStats)
  }

  // 获取需求关联的版本 - GET /versions/requirements/{requirement_id}/versions
  async getRequirementVersions(requirementId: string, params: { skip?: number; limit?: number } = {}): Promise<Version[]> {
    const response = await request.get<ApiResponse<Version[]>>(`/versions/requirements/${requirementId}/versions`, {
      params,
      showLoading: true,
      loadingText: '加载需求版本...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, [] as Version[])
  }

  // ===== 以下是保持向后兼容的旧方法 =====

  // 获取版本详情 - 兼容旧方法名
  async getVersionDetail(id: string): Promise<VersionDetailResponse> {
    const response = await this.getVersionById(id)
    if (response.success && response.data) {
      return response.data
    }
    throw new Error(response.message || '获取版本详情失败')
  }
  
  // 获取版本历史 - 兼容方法
  async getVersionHistory(id: string): Promise<any> {
    return this.getVersionChangeHistory(id, {})
  }

  // 添加任务关联 - 兼容旧方法名
  async addTaskAssociation(versionId: string, taskId: string): Promise<VersionTaskRelation> {
    return this.addTaskToVersion(versionId, { task_id: taskId, relation_type: RelationType.INCLUDED })
  }

  // 移除任务关联 - 兼容旧方法名
  async removeTaskAssociation(versionId: string, taskId: string): Promise<void> {
    await this.removeTaskFromVersion(versionId, taskId)
  }

  // 添加缺陷关联 - 兼容旧方法名
  async addDefectAssociation(versionId: string, defectId: string, config?: CustomAxiosRequestConfig): Promise<VersionDefectRelation> {
    return this.addDefectToVersion(versionId, { defect_id: defectId, relation_type: RelationType.FIXED_IN }, config)
  }

  // 获取版本关联任务 - GET /versions/{version_id}/tasks
  async getVersionTasks(id: string, params: GetVersionTasksParams = {}): Promise<VersionTaskRelation[]> {
    const requestParams: any = {}
    if (params.skip !== undefined) requestParams.skip = params.skip
    if (params.limit !== undefined) requestParams.limit = params.limit
    if (params.status) requestParams.status = params.status
    if (params.relation_type) requestParams.relation_type = params.relation_type

    const response = await request<ApiResponse<VersionTaskRelation[]>>({
      url: `/versions/${id}/tasks`,
      method: 'get',
      params: requestParams
    })
    
    return extractResponseData(response, [] as VersionTaskRelation[])
  }

  // 获取版本关联缺陷 - GET /versions/{version_id}/defects
  async getVersionDefects(id: string, params: GetVersionDefectsParams = {}): Promise<VersionDefectRelation[]> {
    const requestParams: any = {}
    if (params.skip !== undefined) requestParams.skip = params.skip
    if (params.limit !== undefined) requestParams.limit = params.limit
    if (params.status) requestParams.status = params.status
    if (params.relation_type) requestParams.relation_type = params.relation_type

    const response = await request<ApiResponse<VersionDefectRelation[]>>({
      url: `/versions/${id}/defects`,
      method: 'get',
      params: requestParams
    })
    
    return extractResponseData(response, [] as VersionDefectRelation[])
  }

  // 获取版本质量报告 - GET /versions/{id}/quality-report
  async getVersionQualityReport(id: string): Promise<any> {
    const response = await request.get<ApiResponse<any>>(`/versions/${id}/quality-report`, {
      showLoading: true,
      loadingText: '生成质量报告...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {} as any)
  }

  // 获取版本变更日志 - GET /versions/{id}/changelog
  async getVersionChangelog(id: string): Promise<any> {
    const response = await request.get<ApiResponse<any>>(`/versions/${id}/changelog`, {
      showLoading: true,
      loadingText: '加载变更日志...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {} as any)
  }

  // 生成版本报告 - GET /versions/{id}/report
  async generateVersionReport(id: string, reportType: string = 'full'): Promise<any> {
    const response = await request.get<ApiResponse<any>>(`/versions/${id}/report`, {
      params: { type: reportType },
      showLoading: true,
      loadingText: '生成版本报告...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {} as any)
  }

  // 批量操作版本 - POST /versions/batch
  async batchOperateVersions(operation: string, versionIds: string[], data: any = {}): Promise<any> {
    const response = await request.post<ApiResponse<any>>('/versions/batch', {
      operation,
      version_ids: versionIds,
      ...data
    }, {
      showLoading: true,
      loadingText: '批量操作中...'
    } as CustomAxiosRequestConfig)
    return extractResponseData(response, {} as any)
  }

  // ========== 版本状态流转相关API ==========

  // 获取版本完成度 - GET /versions/{id}/completion
  async getCompletion(versionId: string): Promise<VersionCompletion> {
    const response = await request.get<ApiResponse<VersionCompletion>>(
      `/versions/${versionId}/completion`
    )
    const result = extractResponseData(response, {} as VersionCompletion)
    if (!result || Object.keys(result).length === 0) {
      throw new Error('获取版本完成度失败：数据为空')
    }
    return result
  }

  // 获取版本流转准备情况 - GET /versions/{id}/transition-readiness
  async getTransitionReadiness(
    versionId: string,
    targetStatus?: string
  ): Promise<VersionTransitionReadiness> {
    const response = await request.get<ApiResponse<VersionTransitionReadiness>>(
      `/versions/${versionId}/transition-readiness`,
      {
        params: targetStatus ? { target_status: targetStatus } : {}
      }
    )
    const result = extractResponseData(response, {} as VersionTransitionReadiness)
    if (!result || Object.keys(result).length === 0) {
      throw new Error('获取流转准备情况失败：数据为空')
    }
    return result
  }

  // 获取允许的状态流转列表 - GET /versions/{id}/allowed-transitions
  async getAllowedTransitions(versionId: string): Promise<{
    allowed_transitions: VersionTransitionRule[]
  }> {
    const response = await request.get<ApiResponse<{
      allowed_transitions: VersionTransitionRule[]
    }>>(`/versions/${versionId}/allowed-transitions`)
    return extractResponseData(response, { allowed_transitions: [] })
  }

  // 手动流转版本状态 - POST /versions/{id}/transition-status
  async transitionStatus(
    versionId: string,
    data: VersionTransitionData
  ): Promise<any> {
    const response = await request.post<ApiResponse<any>>(
      `/versions/${versionId}/transition-status`,
      data
    )
    return extractResponseData(response, {} as any)
  }

  // 提交状态流转审批申请 - POST /versions/{id}/transition-approval
  async submitTransitionApproval(
    versionId: string,
    data: VersionTransitionRequest
  ): Promise<VersionTransitionApproval> {
    const response = await request.post<ApiResponse<VersionTransitionApproval>>(
      `/versions/${versionId}/transition-approval`,
      data
    )
    const result = extractResponseData(response, {} as VersionTransitionApproval)
    if (!result || Object.keys(result).length === 0) {
      throw new Error('提交审批申请失败：数据为空')
    }
    return result
  }

  // 审批流转申请 - POST /transition-approvals/{id}/approve
  async approveTransitionRequest(
    approvalId: string,
    data: ApprovalActionData
  ): Promise<any> {
    const response = await request.post<ApiResponse<any>>(
      `/versions/transition-approvals/${approvalId}/approve`,
      data
    )
    return extractResponseData(response, {} as any)
  }

  // 获取待审批列表 - GET /transition-approvals/pending
  async getPendingApprovals(projectId?: string): Promise<{
    approvals: VersionTransitionApproval[]
  }> {
    const response = await request.get<ApiResponse<{
      approvals: VersionTransitionApproval[]
    }>>('/versions/transition-approvals/pending', {
      params: projectId ? { project_id: projectId } : {}
    })
    return extractResponseData(response, { approvals: [] })
  }

  // 获取审批历史列表 - GET /transition-approvals/history
  async getApprovalHistory(params?: {
    projectId?: string
    status?: string
    skip?: number
    limit?: number
  }): Promise<{
    approvals: VersionTransitionApproval[]
    total: number
    skip: number
    limit: number
  }> {
    const response = await request.get<ApiResponse<{
      approvals: VersionTransitionApproval[]
      total: number
      skip: number
      limit: number
    }>>('/versions/transition-approvals/history', {
      params: {
        project_id: params?.projectId,
        status: params?.status,
        skip: params?.skip || 0,
        limit: params?.limit || 20
      }
    })
    return extractResponseData(response, {
      approvals: [],
      total: 0,
      skip: params?.skip || 0,
      limit: params?.limit || 20
    })
  }

  // 取消审批申请 - POST /transition-approvals/{id}/cancel
  async cancelApprovalRequest(approvalId: string): Promise<any> {
    const response = await request.post<ApiResponse<any>>(
      `/versions/transition-approvals/${approvalId}/cancel`
    )
    return extractResponseData(response, {} as any)
  }

  // 导出版本数据 - GET /versions/export
  async exportVersions(params: any = {}): Promise<Blob> {
    const response = await request.get('/versions/export', {
      params,
      responseType: 'blob',
      showLoading: true,
      loadingText: '导出数据中...'
    } as CustomAxiosRequestConfig)
    return response.data
  }

  // 导入版本数据 - POST /versions/import
  async importVersions(file: File): Promise<any> {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await request.post<ApiResponse<any>>('/versions/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      showLoading: true,
      loadingText: '导入数据中...'
    } as CustomAxiosRequestConfig)
    return response.data.data
  }
}

// 导出API实例
export const versionAPI = new VersionAPI()

// 导出所有接口和类型
export default versionAPI

// 导出VersionAPI类供其他模块使用
export { VersionAPI }